package com.suneast.suneaststore.wxapi;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.wechat.LatteWeChat;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;
import com.suneast.suneaststore.util.net.callback.IError;
import com.suneast.suneaststore.util.net.callback.IFailure;
import com.suneast.suneaststore.util.net.callback.ISuccess;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxentry);
        ButterKnife.bind(this);
        //这个必须写在onCreate中
        LatteWeChat.getInstance().getWXAPI().handleIntent(getIntent(), this);
    }

    @BindView(R.id.tv_user_info)
    TextView textView;

    @BindView(R.id.img_head)
    ImageView headImg;

    @OnClick({R.id.btn_exit_activity})
    public void onViewClick(View view) {
        if (view.getId() == R.id.btn_exit_activity) {
            finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        LatteWeChat.getInstance().getWXAPI().handleIntent(getIntent(), this);
    }

    //微信发送请求到第三方应用后的回调
    @Override
    public void onReq(BaseReq baseReq) {
    }

    //第三方应用发送请求到微信后的回调
    @Override
    public void onResp(BaseResp baseResp) {
        SendAuth.Resp resp = (SendAuth.Resp) baseResp;
        final String code = resp.code;
        final StringBuilder authUrl = new StringBuilder();
        LatteLogger.d("userInfoUrl", "onResp:errCode = " + baseResp.errCode);
        Log.e("userInfoUrl", "onResp: code = " + resp.code);
        Log.e("userInfoUrl", "onResp: state =" + resp.state);
        Log.e("userInfoUrl", "onResp: lang = " + resp.lang);
        Log.e("userInfoUrl", "onResp: country = " + resp.country);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK: { //用户同意授权

                authUrl
                        .append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
                        .append(LatteWeChat.APP_ID)
                        .append("&secret=")
                        .append(LatteWeChat.APP_SECRET)
                        .append("&code=")
                        .append(code)
                        .append("&grant_type=authorization_code");
                LatteLogger.d("userInfoUrl", authUrl.toString());
                getAuth(authUrl.toString());
            }
            break;
            case BaseResp.ErrCode.ERR_USER_CANCEL: { //用户取消授权
                Toast.makeText(this, "微信用户取消授权", Toast.LENGTH_SHORT).show();
            }
            break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED: { //用户拒绝授权
                Toast.makeText(this, "微信用户拒绝授权", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

    private void getAuth(String authUrl) {
        RestClient
                .builder()
                .url(authUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        LatteLogger.d("userInfoUrl", response);
                        final JSONObject authObj = JSON.parseObject(response);
                        final String accessToken = authObj.getString("access_token");
                        final String openId = authObj.getString("openid");

                        final StringBuilder userInfoUrl = new StringBuilder();
                        userInfoUrl
                                .append("https://api.weixin.qq.com/sns/userinfo?access_token=")
                                .append(accessToken)
                                .append("&openid=")
                                .append(openId)
                                .append("&lang=")
                                .append("zh_CN");
                        LatteLogger.d("userInfoUrl", userInfoUrl.toString());
                        getUserInfo(userInfoUrl.toString());

                    }
                })
                .build()
                .get();
    }

    private void getUserInfo(String userInfoUrl) {
        RestClient
                .builder()
                .url(userInfoUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        //用户登录成功后回调
                        LatteLogger.d("userInfoUrl", response);
                        JSONObject userInfoObj = JSON.parseObject(response);
                        String openId = userInfoObj.getString("openid");
                        String nickName = userInfoObj.getString("nickname");
                        String sex = userInfoObj.getString("sex");
                        String language = userInfoObj.getString("language");
                        String city = userInfoObj.getString("city");
                        String province = userInfoObj.getString("province");
                        String country = userInfoObj.getString("country");
                        String headimg = userInfoObj.getString("headimgurl");
                        String unionId = userInfoObj.getString("unionid");
                        String changeLine = "\r\n";
                        textView.setText(openId + changeLine +
                                nickName + changeLine +
                                sex + changeLine +
                                language + changeLine +
                                city + changeLine +
                                province + changeLine +
                                country + changeLine +
                                headimg + changeLine +
                                unionId + changeLine
                        );
                        Glide.with(headImg.getContext()).load(headimg).into(headImg);
                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .get();
    }

    private void refreshToken(String tokenStr) {
        final StringBuilder refreshTokenUrl = new StringBuilder();
        refreshTokenUrl.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
                .append(LatteWeChat.APP_ID)
                .append("&grant_type=refresh_token&refresh_token=")
                .append(tokenStr);
        RestClient
                .builder()
                .url(refreshTokenUrl.toString())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {

                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .get();
    }


}
